<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>蜂农产业关键指标</h2>
      <p>实时统计蜂农数量、养蜂规模及蜂蜜产量等核心数据</p>
    </div>

    <!-- 指标卡片区域 -->
    <el-row :gutter="20" class="stat-card-row">
      <!-- 蜂农总数 -->
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon farmer-icon">
              <svg-icon icon-class="user" />
            </div>
            <div class="stat-info">
              <p class="stat-label">蜂农总数</p>
              <p class="stat-value">{{ farmerTotal }}</p>
              <p class="stat-desc">
                <span :class="farmerTrendClass">{{ farmerTrend }}%</span>
                <span>较上月</span>
              </p>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 活跃蜂农数 -->
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon active-icon">
              <svg-icon icon-class="user-active" />
            </div>
            <div class="stat-info">
              <p class="stat-label">活跃蜂农数</p>
              <p class="stat-value">{{ activeFarmerTotal }}</p>
              <p class="stat-desc">
                <span :class="activeTrendClass">{{ activeTrend }}%</span>
                <span>较上月</span>
              </p>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 养蜂总面积 -->
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon area-icon">
              <svg-icon icon-class="area" />
            </div>
            <div class="stat-info">
              <p class="stat-label">养蜂总面积(亩)</p>
              <p class="stat-value">{{ totalArea.toFixed(2) }}</p>
              <p class="stat-desc">
                <span :class="areaTrendClass">{{ areaTrend }}%</span>
                <span>较上月</span>
              </p>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 蜂蜜总产量 -->
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon honey-icon">
              <svg-icon icon-class="honey" />
            </div>
            <div class="stat-info">
              <p class="stat-label">蜂蜜总产量(kg)</p>
              <p class="stat-value">{{ totalHoney.toFixed(2) }}</p>
              <p class="stat-desc">
                <span :class="honeyTrendClass">{{ honeyTrend }}%</span>
                <span>较上月</span>
              </p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 产量趋势图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div class="chart-header">
            <span>近6个月蜂蜜产量趋势</span>
            <el-select 
              v-model="chartType" 
              placeholder="选择图表类型" 
              class="chart-type-select"
              @change="handleChartTypeChange"
            >
              <el-option label="折线图" value="line" />
              <el-option label="柱状图" value="bar" />
              <el-option label="面积图" value="area" />
              <el-option label="散点图" value="scatter" />
            </el-select>
          </div>
          <div ref="honeyChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { listFarmer } from '@/api/farmer/farmer'; // 蜂农数据
import { listBeearea } from '@/api/farmer/beearea'; // 养蜂区域数据
import * as echarts from 'echarts';
import { ElMessage, ElSelect, ElOption } from 'element-plus';

// 统计数据
const farmerTotal = ref(0); // 蜂农总数
const activeFarmerTotal = ref(0); // 活跃蜂农数（状态为1的蜂农）
const totalArea = ref(0); // 养蜂总面积
const totalHoney = ref(0); // 蜂蜜总产量

// 图表类型选择
const chartType = ref('line'); // 默认折线图

// 趋势数据（模拟，实际可从接口获取）
const farmerTrend = ref(5.2);
const activeTrend = ref(3.8);
const areaTrend = ref(-1.2);
const honeyTrend = ref(8.5);

// 趋势样式计算
const farmerTrendClass = computed(() => farmerTrend.value >= 0 ? 'trend-up' : 'trend-down');
const activeTrendClass = computed(() => activeTrend.value >= 0 ? 'trend-up' : 'trend-down');
const areaTrendClass = computed(() => areaTrend.value >= 0 ? 'trend-up' : 'trend-down');
const honeyTrendClass = computed(() => honeyTrend.value >= 0 ? 'trend-up' : 'trend-down');

// 图表实例
let honeyChartInstance = null;

// 获取统计数据
const loadStatsData = async () => {
  try {
    // 1. 蜂农数据
    const farmerRes = await listFarmer({ pageNum: 1, pageSize: 1000 });
    farmerTotal.value = farmerRes.rows.length;
    activeFarmerTotal.value = farmerRes.rows.filter(f => f.status === 1).length;

    // 2. 养蜂区域数据（计算总面积）
    const areaRes = await listBeearea({ pageNum: 1, pageSize: 1000 });
    totalArea.value = areaRes.rows.reduce((sum, item) => sum + (item.area || 0), 0);

    // 3. 蜂蜜产量数据
    totalHoney.value = farmerRes.rows.reduce((sum, item) => sum + (item.honeyProduction || 0), 0);

    // 初始化图表
    initHoneyChart();
  } catch (error) {
    ElMessage.error('数据加载失败：' + error.message);
    console.error(error);
  }
};

// 初始化产量趋势图表
const initHoneyChart = () => {
  if (honeyChartInstance) {
    honeyChartInstance.dispose();  // 销毁旧实例
  }
  
  // 确保DOM元素存在
  if (!honeyChart.value) {
    console.error('图表容器不存在');
    return;
  }
  
  honeyChartInstance = echarts.init(honeyChart.value);

  // 模拟近6个月数据（实际应从接口获取）
  const months = ['1月', '2月', '3月', '4月', '5月', '6月'];
  const outputData = [1200, 1900, 1500, 2400, 2800, 3200];
  
  // 根据选择的图表类型设置不同的配置
  const seriesConfig = {
    line: {
      type: 'line',
      smooth: false,
      itemStyle: { color: '#4e8542' },
      lineStyle: { color: '#4e8542' }
    },
    bar: {
      type: 'bar',
      itemStyle: { color: '#1890ff' }
    },
    area: {
      type: 'line',
      smooth: true,
      areaStyle: { color: 'rgba(78, 133, 66, 0.2)' },
      itemStyle: { color: '#4e8542' },
      lineStyle: { color: '#4e8542' }
    },
    scatter: {
      type: 'scatter',
      symbolSize: 10,
      itemStyle: { color: '#722ed1' }
    }
  };

  honeyChartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(100,225,0,0.7)'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      name: '月份',
      axisLabel: {
        rotate: 30,
        color: '#666'
      }
    },
    yAxis: { type: 'value', name: '产量(kg)' },
    series: [{
      name: '蜂蜜产量',
      data: outputData,
      ...seriesConfig[chartType.value] // 应用所选图表类型的配置
    }]
  });
};

// 处理图表类型变更
const handleChartTypeChange = () => {
  initHoneyChart(); // 重新初始化图表
};

// 组件生命周期
onMounted(() => {
  loadStatsData();
  window.addEventListener('resize', () => {
    if (honeyChartInstance) honeyChartInstance.resize();
  });
});

onUnmounted(() => {
  if (honeyChartInstance) {
    honeyChartInstance.dispose();
    honeyChartInstance = null;
  }
});

// 图表容器引用
const honeyChart = ref(null);
</script>

<style scoped>
.page-header {
  margin: 16px 0 24px;
}

.page-header h2 {
  margin: 0 0 8px;
  font-size: 20px;
  color: #1d2129;
}

.page-header p {
  margin: 0;
  color: #86909c;
}

.stat-card-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.stat-icon svg {
  width: 24px;
  height: 24px;
}

.farmer-icon {
  background: #e8f4fd;
  color: #1890ff;
}

.active-icon {
  background: #e6f7ef;
  color: #00b42a;
}

.area-icon {
  background: #fff7e8;
  color: #faad14;
}

.honey-icon {
  background: #f6e8ff;
  color: #722ed1;
}

.stat-label {
  margin: 0 0 4px;
  font-size: 14px;
  color: #86909c;
}

.stat-value {
  margin: 0 0 4px;
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
}

.stat-desc {
  margin: 0;
  font-size: 12px;
  color: #86909c;
}

.trend-up {
  color: #00b42a;
}

.trend-down {
  color: #f53f3f;
}

.chart-row {
  margin-top: 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-type-select {
  width: 180px;
}
</style>
